"""
Logging utilities for the DingTalk Card Sender
"""
import logging
import os
from logging.handlers import RotatingFileHandler
from datetime import datetime


# Create logs directory if it doesn't exist
LOGS_DIR = "logs"
os.makedirs(LOGS_DIR, exist_ok=True)


def setup_logger(name: str, log_file: str, level=logging.INFO):
    """
    Set up a logger with rotating file handler
    """
    # Create formatter
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    # Create file handler with rotation (max 5MB, keep 5 files)
    file_handler = RotatingFileHandler(
        os.path.join(LOGS_DIR, log_file),
        maxBytes=5*1024*1024,  # 5MB
        backupCount=5
    )
    file_handler.setFormatter(formatter)
    
    # Create logger
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(file_handler)
    
    # Also add console handler for development
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    
    return logger


# Application loggers
app_logger = setup_logger('ding_card_sender_app', 'app.log')
api_logger = setup_logger('ding_card_sender_api', 'api.log')
security_logger = setup_logger('ding_card_sender_security', 'security.log')


def log_api_call(endpoint: str, method: str, ip_address: str, user: str = None, status_code: int = 200):
    """
    Log API calls
    """
    api_logger.info(f"API Call: {method} {endpoint} | IP: {ip_address} | User: {user or 'Anonymous'} | Status: {status_code}")


def log_security_event(event_type: str, message: str, ip_address: str = None, user: str = None):
    """
    Log security-related events
    """
    security_logger.warning(f"Security Event: {event_type} | Message: {message} | IP: {ip_address or 'Unknown'} | User: {user or 'Unknown'}")


def log_error(message: str, endpoint: str = None, user: str = None):
    """
    Log errors
    """
    app_logger.error(f"Error: {message} | Endpoint: {endpoint or 'Unknown'} | User: {user or 'Unknown'}")


def log_info(message: str, endpoint: str = None, user: str = None):
    """
    Log info messages
    """
    app_logger.info(f"Info: {message} | Endpoint: {endpoint or 'Unknown'} | User: {user or 'Unknown'}")